<template>
  <div>
    <p style="font-size: 20px">{{ msg }}</p>
    <!-- 显示药品列表 -->
    <el-table :data="pagedStock" style="width: 100%">
      <el-table-column prop="new_id" label="编号" width="80"/>
      <el-table-column prop="stock_quantity" label="库存数量"/>
      <el-table-column prop="address" label="仓储地址"/>
      <el-table-column prop="drug_name" label="药品名称"/>
      <el-table-column prop="stock_warning" label="库存预警"/>
      <el-table-column align="right">
        <!--        delete与edit的实现-->
        <!--        Delete button -->
        <template #default="scope">
          <div style="display: flex;align-items: center;" v-if="haspermission(['admin','manager'])">
            <!-- Edit button with popover -->
            <el-button size="small" type="danger" @click="open_delete(scope.row)">Delete</el-button>
            <el-popover placement="right" :width="320" trigger="click">
              <template #reference>
                <el-button size="small" @click="setValue(scope.row)">Edit</el-button>
              </template>
              <div>
                <form @submit="handleEdit">
                  <p>向后端修改库存信息:</p>
                  <label>数量：</label>
                  <el-input
                      v-model="stockEdit.stock_quantity"
                      style="width: 240px"
                      show-word-limit
                      type=number
                  />
                  <label>地址：</label>
                  <el-input
                      v-model="stockEdit.address"
                      maxlength="20"
                      style="width: 240px"
                      show-word-limit
                      type=text
                  /><label>名称：</label>
                  <el-input
                      v-model="stockEdit.drug_name"
                      maxlength="20"
                      style="width: 240px"
                      show-word-limit
                      type=text
                  />
                  <label>类别：</label>
                  <el-radio-group v-model="stockEdit.stock_warning">
                    <el-radio label="low">预警: Low</el-radio>
                    <el-radio label="normal">预警: Normal</el-radio>
                  </el-radio-group>
                  <div style="margin: 20px 0"/>
                  <el-button type="info" round @click="handleEdit(scope.row)" size="small">提交修改</el-button>
                </form>
              </div>
            </el-popover>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        style="margin-top: 30px"
        layout="prev, pager, next"
        :total="total"
        v-model="currentPage"
        :page-size="pageSize"
        @current-change="handlePageChange"
    />

    <div style="display: flex; align-items: center;">
      <!-- 添加药品的表单 -->
      <form @submit="drugSubmit" ref="addForm">
        <h3>向后端添加库存的表单:</h3>
        <el-input
            v-model="inputStock.stock_quantity"
            style="width: 240px"
            maxlength="20"
            placeholder="药品数量"
            show-word-limit
            type=number
        />
        <div style="margin: 5px 0"/>
        <el-input
            v-model="inputStock.address"
            maxlength="20"
            style="width: 240px"
            placeholder="药品仓储地址"
            show-word-limit
            type="text"
        /><div style="margin: 5px 0"/>
        <el-input
            v-model="inputStock.drug_name"
            maxlength="20"
            style="width: 240px"
            placeholder="药品名称"
            show-word-limit
            type="text"
        /><div style="margin: 5px 0"/>
        <el-radio-group v-model="inputStock.stock_warning">
          <el-radio label="low">预警: Low</el-radio>
          <el-radio label="normal">预警: Normal</el-radio>
        </el-radio-group>
        <hr>
        <el-button type="success" round @click="drugSubmit">提交</el-button>
      </form>
      <div style="padding: 5%"></div>
      <div>
        <h3>查询预警的表单1</h3>
        <label>药品名称：</label>
        <el-input type="text" style="width: 240px" v-model="name_pattern"/>
        <div style="margin: 20px 0"/>
        <el-popover placement="right" :width="600" trigger="click">
          <template #reference>
            <el-button type="info" @click="findStock">按名称查找</el-button>
          </template>
          <el-table :data="suser">
            <el-table-column prop="new_id" label="编号" width="80"/>
            <el-table-column prop="stock_quantity" label="库存数量"/>
            <el-table-column prop="address" label="仓储地址"/>
            <el-table-column prop="drug_name" label="药品名称"/>
            <el-table-column prop="stock_warning" label="库存预警"/>
          </el-table>
        </el-popover>
      </div>
      <div style="padding: 5%"></div>
      <div>
        <h3>查询预警的表单2</h3>
        <label>预警类别：</label>
        <el-radio-group v-model="type">
          <el-radio label="low">预警: Low</el-radio>
          <el-radio label="normal">预警: Normal</el-radio>
        </el-radio-group>
        <div style="margin: 20px 0"/>
        <el-popover placement="right" :width="600" trigger="click">
          <template #reference>
            <el-button type="info" @click="findStock2">预警查找</el-button>
          </template>
          <el-table :data="suser">
            <el-table-column prop="new_id" label="编号" width="80"/>
            <el-table-column prop="stock_quantity" label="库存数量"/>
            <el-table-column prop="address" label="仓储地址"/>
            <el-table-column prop="drug_name" label="药品名称"/>
            <el-table-column prop="stock_warning" label="库存预警"/>
          </el-table>
        </el-popover>
      </div>
      <div style="padding: 5%"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {computed, h, onMounted, ref, watch} from 'vue';
import {getStock, postStock, deleteStock, updateStock, findByStockTitle, findByStockType} from '@/api/api'
import {ElMessage, ElMessageBox} from "element-plus";
import {useLoginStore} from "@/stores";

const store = useLoginStore();

function haspermission(allowance: string[]) {
  return allowance.indexOf(store.role) !== -1;
}
const msg = ref('欢迎来到库存管理板块');

const inputStock = ref({
  stock_quantity:Number,
  address:"",
  drug_name:"",
  stock_warning:""
});

//增
async function drugSubmit() {
  try {
    const response = await postStock(inputStock.value.stock_quantity,inputStock.value.address,inputStock.value.drug_name,inputStock.value.stock_warning);
    console.log(response);
    await loadStocks();
    // 清空输入字段
    inputStock.value = {stock_quantity:Number, address:"", drug_name:"", stock_warning:""};
  } catch (error) {
    console.error('Error submitting drug:', error);
    // 在这里可以添加错误处理的逻辑，比如显示错误信息给预警
  }
}

//删
async function deleteStockAndHandleResponse(id: number) {
  try {
    const response = await deleteStock(id);
    console.log('Stock deleted successfully', response);
    await loadStocks()
  } catch (error) {
    console.error('Error deleting Stock', error);
  }
}

const open_delete = (obj: any) => {
  ElMessageBox({
    title: 'Message',
    message: h('p', null, [
      h('span', null, '请注意删除操作是不可逆的'),
      h('i', {style: 'color: teal'}, '数据库会同步变化'),
    ]),
    showCancelButton: true,
    confirmButtonText: '确认删除',
    cancelButtonText: '取消删除',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        deleteStockAndHandleResponse(obj.id);
        // window.location.reload()
        done();
      } else {
        done();
      }
    },
  }).then((action) => {
    ElMessage({
      type: 'info',
      message: `操作结果: ${action === 'confirm' ? '删除成功' : '已取消删除'}`,
    });
  });
}

//改
const stockEdit = ref({
  stock_quantity:0,
  address:"",
  drug_name:"",
  stock_warning:""
})

function setValue(obj: any) {
  stockEdit.value.stock_quantity = obj.stock_quantity;
  stockEdit.value.address = obj.address;
  stockEdit.value.drug_name = obj.drug_name;
  stockEdit.value.stock_warning = obj.stock_warning;
}


async function handleEdit(obj: any) {
  try {
    const response = await updateStock(obj.id, stockEdit.value)
    console.log("Stock edit successfully", response)
    await loadStocks()
    ElMessage({
      type: 'info',
      message: `操作结果:'修改成功'`,
    });
  } catch (error) {
    console.error(error);
  }
}

//查
const drugs = ref([
  {id: 1, stock_quantity:0, address:"", drug_name:"", stock_warning:"", new_id: 0},
  {id: 2, stock_quantity:0, address:"", drug_name:"", stock_warning:"", new_id: 0},
])
let currentPage = ref(1)
const pageSize = ref(6)
const total = ref(drugs.value.length) // 计算总记录数

watch(drugs, (newValue) => {
  total.value = newValue.length;
});
const pagedStock = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;

  return drugs.value.slice(startIndex, endIndex);
});

function handlePageChange(newPage: number) {
  currentPage.value = newPage
}

async function loadStocks() {
  try {
    const response = await getStock();
    // 假设 response.data 是一个药品数组
    drugs.value = response.data;
    let new_index = 1;
    for (let oneMoney of drugs.value) {
      oneMoney.new_id = new_index;
      new_index++;
    }
  } catch (error) {
    // 处理错误情况
    console.error('Error loading drugs:', error);
  }
}
onMounted(() => {
  loadStocks();
});

//特殊查寻
const name_pattern = ref('')
const type = ref('')
const suser = ref([
  {id: 1, stock_quantity:0, address:"", drug_name:"", stock_warning:"", new_id: 0},
])

async function findStock() {
  try {
    const response = await findByStockTitle(name_pattern.value);
    suser.value = response.data
    console.log(response)
    console.log(suser.value)
    let index = 1
    for (let i of suser.value) {
      i.new_id = index
      index++
    }
  } catch (error) {
    console.error("Error finding drug:", error);
  }
}
async function findStock2() {
  try {
    const response = await findByStockType(type.value);
    suser.value = response.data
    console.log(response)
    console.log(suser.value)
    let index = 1
    for (let i of suser.value) {
      i.new_id = index
      index++
    }
  } catch (error) {
    console.error("Error finding drug:", error);
  }
}
</script>